package com.example.save;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import java.util.List;

import static java.lang.Integer.parseInt;

public class fragment6 extends Fragment {
    private Button button3;
    private Button button4;


    public fragment6(){
        super(R.layout.fragment6);
    }

    @Override
    public void onViewCreated(View view, Bundle savedStanceSate){
        super.onViewCreated(view,savedStanceSate);

        User user=new User();

        final EditText usernameEdit=getView().findViewById(R.id.getNameEdit);
        final EditText ageEdit=getView().findViewById(R.id.getAgeEdit2);
        final TextView contentTextView=getView().findViewById(R.id.textView2);

        MyRoomDatabase db = MyRoomDatabase.getInstance(getActivity());

        button3=getActivity().findViewById(R.id.button5);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String username=usernameEdit.getText().toString();
                int age=parseInt(ageEdit.getText().toString());
                user.username=username;
                user.age=age;
                db.userDao().insert(user);
                showUsers(db.userDao().getAll());
            }


            private void showUsers(List<User> user){
                StringBuilder stringBuilder=new StringBuilder();
                for(User users:user){
                    stringBuilder.append("id:").append(users.id+" ")
                            .append("username:").append(users.username+" ")
                            .append("age:").append(users.age)
                            .append("\n");
                }
                contentTextView.setText(stringBuilder.toString());
            }
        });

        button4=getActivity().findViewById(R.id.button6);
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showUsers(db.userDao().searchUsersByAge(18));
            }

            private void showUsers(List<User> user){
                StringBuilder stringBuilder=new StringBuilder();
                for(User users:user){
                    stringBuilder.append("id:").append(users.id+" ")
                            .append("username:").append(users.username+" ")
                            .append("age:").append(users.age)
                            .append("\n");
                }
                contentTextView.setText(stringBuilder.toString());
            }
        });

    }
}
